<template>
  <div class="app-container">
    <!-- <div style="padding: 5px 0 20px">
      <div
        class="Grid Grid--1of5 Grid--center Grid--justifyCenter text-center"
        style="width: 770px"
      >
        <div class="Grid-cell" style="border: 1px solid #ebeef5; padding: 5px 0">
          <div>发布总数</div>
          <div class="text-xl">{{ total.article }}</div>
        </div>
        <div class="Grid-cell" style="border: 1px solid #ebeef5; padding: 5px 0">
          <div>总销量</div>
          <div class="text-xl">{{ total.sales }}</div>
        </div>
        <div class="Grid-cell" style="border: 1px solid #ebeef5; padding: 5px 0">
          <div>总金额</div>
          <div v-if="total.amount != undefined" class="text-xl">&yen;{{ total.amount }}</div>
        </div>
        <div class="Grid-cell" style="border: 1px solid #ebeef5; padding: 5px 0">
          <div>实收总额</div>
          <div v-if="total.pay_amount != undefined" class="text-xl">
            &yen;{{ total.pay_amount }}
          </div>
        </div>
        <div class="Grid-cell" style="border: 1px solid #ebeef5; padding: 5px 0">
          <div>总浏览量</div>
          <div class="text-xl">{{ total.views }}</div>
        </div>
      </div>
    </div> -->
    <!-- 查询 -->
    <el-row class="elRow">
      <el-col>
        <el-button class="mb-2 mr-3" type="primary" @click="add"
          ><el-icon class="mr-1" color="#fff"><Plus /></el-icon>创建方案</el-button
        >
        <el-button class="mb-2 mr-6" type="primary" @click="centerDialogVisible = true"
          >收款码</el-button
        >
        <el-input
          v-model="query.search_value"
          class="ya-search-value mb-2 mr-6"
          placeholder="请输入标题关键字"
          clearable
        />
        <el-select
          v-model="query.date_field"
          class="ya-date-field mb-2 mr-6"
          placeholder="时间类型"
        >
          <el-option value="create_time" label="创建时间" />
          <el-option value="update_time" label="修改时间" />
          <el-option value="release_time" label="发布时间" />
        </el-select>
        <el-date-picker
          v-model="query.date_value"
          type="datetimerange"
          class="ya-date-value mb-2 mr-6"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="search()"
          popper-class="datetimerange-style"
          :shortcuts="dateShortcuts"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date(2024, 1, 1, 0, 0, 0), new Date(2024, 1, 1, 23, 59, 59)]"
        />
        <el-select
          v-model="query.category_ids"
          class="ya-search-value mb-2 mr-6"
          placeholder="类别"
        >
          <el-option value="" label="全部" />
          <el-option value="3" label="足球" />
          <el-option value="4" label="篮球" />
        </el-select>
        <el-tree-select
          v-if="role_ids.includes(1) || role_ids.includes(4)"
          class="ya-search-value mb-2 mr-6"
          v-model="query.dept_id"
          :data="dept_list"
          :props="{
            children: 'children', //自定义属性
            label: 'dept_name',
            value: 'dept_id'
          }"
          filterable
          clearable
          placeholder="所属组"
          default-expand-all
          :render-after-expand="false"
          check-strictly
        />
        <el-select
          v-if="role_ids.includes(1) || role_ids.includes(3) || role_ids.includes(4)"
          v-model="query.user_id"
          filterable
          class="ya-search-value mr-6 mb-2"
          clearable
          placeholder="请选择销售人员"
        >
          <el-option
            v-for="item in user_list"
            :key="item.user_id"
            :label="item.nickname"
            :value="item.user_id"
          />
        </el-select>
        <el-select
          v-model="query.market_id"
          class="ya-search-value mr-6 mb-2"
          clearable
          placeholder="营销方案"
        >
          <el-option
            v-for="(item, index) in marketData"
            :key="index"
            :value="item.id"
            :label="item.title"
          />
        </el-select>
        <el-button class="mb-2 ml-10 mr-2" type="primary" @click="search()">查询</el-button>
        <el-button class="mb-2" title="重置" @click="refresh()">重置 </el-button>
      </el-col>
    </el-row>
    <!-- 合成收款码 -->
    <el-dialog
      class="codeStyle"
      v-model="centerDialogVisible"
      :close-on-click-modal="false"
      title="合成收款码"
      width="430px"
      center
    >
      <el-form
        class="Grid Grid--justifyCenter"
        ref="ruleFormRef"
        style="max-width: 600px; padding: 10px 0"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        :size="formSize"
        status-icon
      >
        <el-form-item label="价格" prop="price" label-width="100px">
          <el-input
            class="ya-select-field"
            type="number"
            style="width: 260px"
            placeholder="请输入价格"
            v-model="ruleForm.price"
          />
        </el-form-item>
        <!-- <el-form-item label="所属公众号" prop="wechat_id" label-width="100px">
          <el-select  style="width: 260px;" class="ya-select-field"
            v-model="ruleForm.wechat_id"
            filterable
            placeholder="请选择公众号"
          >
            <el-option
              v-for="(item, index) in wechat_list"
              :key="index"
              :label="item.title"
              :value="item.wechat_id"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="getGenerate()" type="primary">&nbsp;&nbsp;生成&nbsp;&nbsp;</el-button>
        </div>
      </template>
    </el-dialog>
    <div style="background-color: #fff; padding: 10px 30px 20px; border-radius: 10px">
      <!-- 列表 -->
      <el-tabs
        v-model="query.draft_status"
        @tab-change="
          (name) => {
            query.draft_status = name
            list()
          }
        "
      >
        <el-tab-pane label="已发布" lazy :name="0">
          <list
            :data="data"
            :draftStatus="0"
            :loading="loading"
            @handle-complete="list"
            @handle-edit="handleEdit"
          />
        </el-tab-pane>
        <el-tab-pane label="收款码" lazy :name="4">
          <list
            :data="data"
            :draftStatus="4"
            :loading="loading"
            @handle-complete="list"
            @handle-edit="handleEdit"
          />
        </el-tab-pane>
        <el-tab-pane label="草稿箱" lazy :name="1">
          <list
            :data="data"
            :draftStatus="1"
            :loading="loading"
            @handle-complete="list"
            @handle-edit="handleEdit"
          />
        </el-tab-pane>
        <el-tab-pane label="模板" lazy :name="3">
          <list
            :data="data"
            :draftStatus="3"
            :loading="loading"
            @handle-complete="list"
            @handle-edit="handleEdit"
          />
        </el-tab-pane>
        <el-tab-pane label="回收站" lazy :name="2">
          <list
            :data="data"
            :draftStatus="2"
            :loading="loading"
            @handle-complete="list"
            @handle-edit="handleEdit"
          />
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <pagination
        v-show="count > 0"
        v-model:total="count"
        v-model:page="query.page"
        v-model:limit="query.limit"
        @pagination="list"
      />

      <!-- <add-edit
        :visible="visible"
        :title="title"
        :data="editData"
        @handle-close="visible = false"
        @handle-complete="list"
      /> -->
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue'
import { arrayColumn } from '@/utils/index'
import { getPageLimit } from '@/utils/settings'
import { list, dele, istop, disable, marketList, add } from '@/api/content/content'
import dayjs from 'dayjs'
// import AddEdit from './cps/add-edit.vue'
import List from './cps/list.vue'
import { useUserStoreHook } from '@/store/modules/user'
import { shortcuts } from '@/utils/index'
import { myUserList } from '@/api/order/statistics'
import defaultSettings from '@/settings'
const userStore = useUserStoreHook()
const amount = (rule, value, callback) => {
  if (value === '') return callback(new Error('输入金额有误!'))
  if (Number(value) > 2999) return callback(new Error('输入的金额不得大于2999.00元!'))
  if (/^[1-9]\d*(,\d{3})*(\.\d{1,2})?$|^0\.\d{1,2}$/.test(value) || value == 0) {
    callback()
  } else {
    callback(new Error('输入金额有误!'))
  }
}
export default {
  name: 'ArticleIndex',
  components: { Pagination, List },

  data() {
    return {
      // 公众号集合
      // wechat_list: [],
      ruleForm: {
        price: '',
        category_ids: [5],
        title: '收款码',
        draft_status: 4,
        wechat_id: ''
      },
      rules: {
        price: [
          {
            required: true,
            validator: amount,
            trigger: 'blur'
          }
        ]
        // wechat_id: [
        //   { required: true, message: '请选择公众号', trigger: 'change' },
        // ],
      },
      centerDialogVisible: false,
      marketData: [], //营销方案
      dateShortcuts: shortcuts,
      painting: {
        width: '550px',
        height: '876px',
        background: '#f4f5f7',
        views: [
          {
            type: 'image',
            url: 'https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/poster/2@2x.png',
            css: {
              top: '20px',
              left: '36px',
              borderRadius: '40px',
              width: '80px',
              height: '80px'
            }
          }
          // ....
        ]
      },
      name: '方案',
      loading: false,
      // idkey: 'content_id',
      data: [],
      total: {},
      // 入参
      query: {
        page: 1,
        limit: getPageLimit(),
        search_field: 'name',
        search_exp: 'like',
        date_field: 'create_time',
        draft_status: 0, // 0-已发布 1-已发布 2-回收站  3-模版
        category_ids: '',
        market_id: '',
        date_value: [
          `${dayjs().startOf('month').format('YYYY-MM-DD')} 00:00:00`,
          `${dayjs().format('YYYY-MM-DD 23:59:59')}`
        ], //默认当天
        dept_id: '',
        user_id: ''
      },
      count: 0,
      selection: [],
      selectIds: '',

      visible: false,
      title: '',
      editData: {},
      role_ids: [],
      user_list: []
    }
  },
  watch: {
    'query.dept_id': {
      handler() {
        this.user_list = []
        this.query.user_id = ''
        if (this.query.dept_id) {
          myUserList({
            dept_id: this.query.dept_id
          })
            .then((res) => {
              console.log(res)
              if (res.code == 200) {
                this.user_list = res.data
              }
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          this.user_list = userStore.user.user_list
        }
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.query.draft_status = this.$route.query.type * 1 || 0
      this.marketList()
      this.user_list = userStore.user.user_list
      this.dept_list = userStore.user.dept_list
      this.role_ids = userStore.user.role_ids
      // this.wechat_list = userStore.user.wechat_list
      if (this.role_ids.includes(3) || this.role_ids.includes(4)) {
        this.query.user_id = userStore.user.user_id
      }
      if (this.$route.query && this.$route.query.textType == 'edit') {
        console.log(this.$route.query, 'this.$route.query')
        this.query = this.$route.query
        this.query.user_id = Number(this.$route.query.user_id)
        this.query.draft_status = Number(this.$route.query.draft_status)
        this.query.dept_id = this.$route.query.dept_id ? Number(this.$route.query.dept_id) : ''
        this.query.market_id = this.$route.query.market_id
          ? Number(this.$route.query.market_id)
          : ''
      }
      this.$forceUpdate()
      this.list()
    })
  },
  methods: {
    // 生成
    getGenerate() {
      this.$refs['ruleFormRef'].validate((valid) => {
        if (valid) {
          add(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.$router.replace(`/article/index?type=${this.ruleForm.draft_status}`)
              this.list()
              this.centerDialogVisible = false
              ElMessage.success(res.msg)
            }
          })
        }
      })
    },
    // 营销列表
    marketList() {
      marketList().then((res) => {
        if (res.code == 200) {
          this.marketData = res.data
        }
      })
    },
    // 创建方案
    add() {
      this.editData = {}
      // visible = true
      // title = '创建方案'
      const storePrefix = defaultSettings.storePrefix
      localStorage.setItem(storePrefix + 'editData', JSON.stringify(this.editData))
      this.query.textType = 'edit'
      this.$router.push({ path: '/article/add-edit-view', query: this.query })
    },
    // 列表
    list() {
      this.loading = true
      list(this.query)
        .then((res) => {
          this.total = res.data.total
          this.data = res.data.list
          this.count = res.data.count
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      const limit = this.query.limit
      this.query = this.$options.data().query
      // this.$refs['table'].clearSort()
      this.query.limit = limit
      if (this.role_ids.includes(3)) {
        this.query.user_id = userStore.user.user_id
      }
      this.list()
    },
    // 排序
    sort(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
        this.list()
      }
    },
    // 操作
    select(selection) {
      this.selection = selection
      this.selectIds = this.selectGetIds(selection).toString()
    },
    selectGetIds(selection) {
      return arrayColumn(selection, this.idkey)
    },
    selectAlert() {
      ElMessageBox.alert('请选择需要操作的' + this.name, '提示', {
        type: 'warning',
        callback: () => {}
      })
    },
    // 修改分类
    // editcate(row) {
    //   editcate({
    //     ids: this.selectGetIds(row),
    //     category_ids: this.form.category_ids
    //   })
    //     .then((res) => {
    //       this.list()
    //       ElMessage.success(res.msg)
    //     })
    //     .catch(() => {
    //       this.loading = false
    //     })
    // },
    // 是否置顶
    istop(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_top = row[0].is_top
        if (select) {
          is_top = this.form.is_top
        }
        istop({
          ids: this.selectGetIds(row),
          is_top: is_top
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 是否热门
    ishot(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_hot = row[0].is_hot
        if (select) {
          is_hot = this.form.is_hot
        }
        ishot({
          ids: this.selectGetIds(row),
          is_hot: is_hot
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 是否推荐
    isrec(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_rec = row[0].is_rec
        if (select) {
          is_rec = this.form.is_rec
        }
        isrec({
          ids: this.selectGetIds(row),
          is_rec: is_rec
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 是否禁用
    disable(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_disable = row[0].is_disable
        if (select) {
          is_disable = this.form.is_disable
        }
        disable({
          ids: this.selectGetIds(row),
          is_disable: is_disable
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 发布时间
    release(row) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        release({
          ids: this.selectGetIds(row),
          release_time: this.form.release_time
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 删除
    dele(row) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        dele({
          ids: this.selectGetIds(row)
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    updateVisible(e) {
      console.log(e)
    },
    // 编辑
    handleEdit(data, type) {
      console.log('-编辑-', data, type)
      let e = JSON.parse(JSON.stringify(data))
      console.log(!type && e.market_ids.length != 0, '77777777')
      this.editData = {
        hits_show: type ? '' : e.hits_show,
        content_id: type ? '' : e.content_id, // 方案id
        // 赛程日期
        match_date: e.match_info ? JSON.parse(e.match_info).match_time.slice(0, 10) : e.match_date,
        category_ids: e.category_ids, // 类型：3 足球 4 篮球
        name: e.name,
        title: e.title, // 方案标题
        expires_time: type ? '' : e.expires_time, // 方案过期时间
        match_info: e.match_info, // 方案关联的赛事(json)
        match_data: e.match_data, // 自定义赛事图标(json)
        price: e.price, // 价格
        description: e.description, // 方案描述
        img_url_list: e.img_url ? e.img_url.split(',') : [], //简介图片墙
        img_url: e.img_url ? e.img_url.split(',') : [], //简介图片墙
        img_url_list_main: e.img_main ? e.img_main.split(',') : [], //正文图片墙
        img_main: e.img_main ? e.img_main.split(',') : [], //正文简介图片墙
        match_nick: e.match_nick, // 方案描述
        kuiper_data: e.kuiper_data, // 图标数据
        content: e.content, // 方案付费内容
        url: e.url, //海报样式
        is_top: e.is_top, // 是否置顶，1是0否
        is_hot: e.is_hot, // 是否热门，1是0否
        is_rec: e.is_rec, // 是否推荐，1是0否
        is_disable: e.is_disable, // 是否禁用，1是0否
        wechat_id: e.wechat_id, // 方案关联公众号
        invisible_ids: e.invisible_ids, // 屏蔽不让查看的会员id,逗号分割
        release_time: type ? '' : e.release_time, // 定时发布时间
        push_fans: e.push_fans, // 方案发布时是否向粉丝推送(1-推送,0-不推送)
        poster_info: e.poster_info, // 海报信息
        draft_status: type ? 1 : e.draft_status, // 0-已发布 1-草稿箱 2-回收站  3-模版
        type: e.type, //方案类型
        vid: e.vid, // 视频id
        vid_img: e.vid_img, // 视频封面地址
        free_duration: e.free_duration, // 试看时长
        duration: e.duration, // 总时长
        market_ids: type ? [] : e.market_ids, //营销方案
        seckill_id: !type && e.market_ids.includes(5) ? e.marketing_tools[5].seckill_id : undefined, //秒杀id
        seckill_price:
          !type && e.market_ids.includes(5) ? e.marketing_tools[5].seckill_price : null, //秒杀价格
        seckill_expire:
          !type && e.market_ids.includes(5) ? e.marketing_tools[5].seckill_expire : '', //秒杀时间
        seckill_stock:
          !type && e.market_ids.includes(5) ? e.marketing_tools[5].seckill_stock : null, //秒杀库存
        surplus_show: !type && e.market_ids.includes(5) ? e.marketing_tools[5].surplus_show : null //秒杀库存
      }
      console.log(type != 'copy' ? e.market_ids : [], 'this.editData')
      this.title = type ? '创建方案' : '编辑方案'
      // this.visible = true
      const storePrefix = defaultSettings.storePrefix
      localStorage.setItem(storePrefix + 'editData', JSON.stringify(this.editData))
      this.query.textType = 'edit'
      this.$router.push({ path: '/article/add-edit-view', query: this.query })
    }
  }
}
</script>
<style>
.codeStyle > .el-dialog__header > .el-dialog__title {
  margin-left: 24px;
}
</style>
<style lang="scss" scoped>
.app-container {
  padding: 0;
  background-color: #efefef;
  height: calc(100vh - 110px);
  .elRow {
    background-color: #fff;
    margin-bottom: 10px;
    padding: 20px 30px 10px;
    border-radius: 10px;
  }
  ::v-deep .el-tabs__nav-wrap {
    padding: 0 22px;
  }
}
::v-deep .el-radio.el-radio--large {
  height: 32px;
}
</style>
